<template>
  <div class="tasks-container">
    <div class="page-header">
      <h2 class="page-title">任务管理</h2>
      <div class="summary-stats">
        <div class="stat-item">
          <span class="stat-value">{{ filteredTasks.length }}</span>
          <span class="stat-label">总任务数</span>
        </div>
        <div class="stat-item">
          <span class="stat-value critical">{{ getTaskCountByPriority('关键任务') }}</span>
          <span class="stat-label">关键任务</span>
        </div>
        <div class="stat-item">
          <span class="stat-value important">{{ getTaskCountByPriority('一般任务') }}</span>
          <span class="stat-label">一般任务</span>
        </div>
        <div class="stat-item">
          <span class="stat-value normal">{{ getTaskCountByPriority('普通任务') }}</span>
          <span class="stat-label">普通任务</span>
        </div>
      </div>
    </div>

    <div class="filter-bar">
      <div class="filter-group">
        <el-select v-model="projectId" placeholder="所属项目" class="filter-item">
          <el-option label="全部项目" value="" />
          <el-option
            v-for="project in projects"
            :key="project.id"
            :label="project.name"
            :value="project.id"
          />
        </el-select>
        <el-select v-model="priority" placeholder="优先级" class="filter-item">
          <el-option label="全部优先级" value="" />
          <el-option label="关键任务" value="关键任务" />
          <el-option label="一般任务" value="一般任务" />
          <el-option label="普通任务" value="普通任务" />
        </el-select>
        <el-select v-model="status" placeholder="任务状态" class="filter-item">
          <el-option label="全部状态" value="" />
          <el-option label="待处理" value="pending" />
          <el-option label="进行中" value="active" />
          <el-option label="已完成" value="completed" />
        </el-select>
      </div>
      <el-button type="primary" @click="showAddTaskDialog" class="add-button">
        <el-icon><Plus /></el-icon>
        新增任务
      </el-button>
    </div>

    <el-table 
      :data="filteredTasks" 
      style="width: 100%; margin-top: 20px"
      border
      stripe
      :default-sort="{prop: 'priority', order: 'ascending'}"
    >
      <el-table-column type="expand">
        <template #default="props">
          <div class="task-detail">
            <div class="detail-item">
              <label>任务描述：</label>
              <span>{{ props.row.description || '暂无任务详细描述' }}</span>
            </div>
            <div class="detail-item" v-if="props.row.remarks">
              <label>备注信息：</label>
              <span>{{ props.row.remarks }}</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="任务" min-width="180">
        <template #default="{ row }">
          <div class="task-name-cell">
            <el-tag 
              :type="getPriorityTagType(row.priority)" 
              effect="dark" 
              size="small"
              class="priority-tag"
            >
              {{ getPriorityShort(row.priority) }}
            </el-tag>
            <span class="task-name">{{ row.name }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="projectName" label="所属项目" width="150" />
      <el-table-column label="负责人" width="120">
        <template #default="{ row }">
          <div class="manager-cell">
            <el-avatar :size="24" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
            <span>{{ row.manager }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="deadline" label="截止日期" width="120" sortable>
        <template #default="{ row }">
          <div class="deadline-cell" :class="{ 'deadline-warning': isDeadlineNear(row.deadline) }">
            <el-icon v-if="isDeadlineNear(row.deadline)"><Warning /></el-icon>
            <span>{{ formatDate(row.deadline) }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="priority" label="优先级" width="120" sortable>
        <template #default="{ row }">
          <el-tag :type="getPriorityType(row.priority)" effect="plain">
            {{ row.priority }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100" sortable>
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">{{ row.statusText }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="进度" width="160">
        <template #default="{ row }">
          <el-progress 
            :percentage="getTaskProgress(row)" 
            :status="getProgressStatus(row.status)"
            :stroke-width="10"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <div class="action-buttons">
            <el-button type="primary" size="small" @click="editTask(row)">编辑</el-button>
            <el-button type="info" size="small" @click="showTaskHistory(row)">
              <el-icon><Clock /></el-icon>
              历史
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 任务表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增任务' : '编辑任务'"
      width="550px"
    >
      <el-form :model="taskForm" label-width="100px" ref="taskFormRef" :rules="taskRules">
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="taskForm.name" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="所属项目" prop="projectId">
          <el-select v-model="taskForm.projectId" style="width: 100%" placeholder="请选择所属项目">
            <el-option
              v-for="project in projects"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="任务描述">
          <el-input 
            v-model="taskForm.description" 
            type="textarea" 
            rows="3" 
            placeholder="请输入任务详细描述" 
          />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="负责人" prop="manager">
              <el-select v-model="taskForm.manager" style="width: 100%" placeholder="请选择负责人">
                <el-option
                  v-for="user in users"
                  :key="user.id"
                  :label="user.name"
                  :value="user.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截止日期" prop="deadline">
              <el-date-picker
                v-model="taskForm.deadline"
                type="date"
                style="width: 100%"
                placeholder="请选择截止日期"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="taskForm.priority" style="width: 100%">
                <el-option label="关键任务" value="关键任务" />
                <el-option label="一般任务" value="一般任务" />
                <el-option label="普通任务" value="普通任务" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="taskForm.status" style="width: 100%">
                <el-option label="待处理" value="pending" />
                <el-option label="进行中" value="active" />
                <el-option label="已完成" value="completed" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="任务进度" v-if="taskForm.status !== 'completed'">
          <el-slider 
            v-model="taskForm.progress" 
            :format-tooltip="formatProgress"
            :disabled="taskForm.status === 'completed'"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input 
            v-model="taskForm.remarks" 
            type="textarea" 
            rows="2" 
            placeholder="备注信息" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button v-if="dialogType === 'edit' && taskForm.status !== 'completed'" 
            type="success" 
            @click="completeTask(taskForm)">
            标记为完成
          </el-button>
          <el-button v-if="dialogType === 'edit'" 
            type="danger" 
            @click="confirmDeleteFromForm">
            删除任务
          </el-button>
          <el-button type="primary" @click="saveTask">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 确认删除对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="删除任务"
      width="400px"
    >
      <div class="delete-confirm">
        <el-icon class="warning-icon"><WarningFilled /></el-icon>
        <p>确定要删除任务 <strong>{{ taskToDelete?.name }}</strong> 吗？</p>
        <p class="warning-text">此操作不可恢复！</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确认删除</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加任务历史记录对话框 -->
    <el-dialog
      v-model="historyDialogVisible"
      title="任务更新历史"
      width="600px"
      destroy-on-close
    >
      <div v-if="currentTask" class="task-history-header">
        <h3>{{ currentTask.name }}</h3>
        <div class="task-basic-info">
          <div class="info-item">
            <span class="label">所属项目：</span>
            <span>{{ currentTask.projectName }}</span>
          </div>
          <div class="info-item">
            <span class="label">负责人：</span>
            <span>{{ currentTask.manager }}</span>
          </div>
          <div class="info-item">
            <span class="label">当前状态：</span>
            <el-tag :type="getStatusType(currentTask.status)">{{ currentTask.statusText }}</el-tag>
          </div>
          <div class="info-item">
            <span class="label">截止日期：</span>
            <span>{{ formatDate(currentTask.deadline) }}</span>
          </div>
          <div class="info-item">
            <span class="label">当前进度：</span>
            <el-progress 
              :percentage="getTaskProgress(currentTask)" 
              :status="getProgressStatus(currentTask.status)"
              :stroke-width="10"
              style="width: 150px"
            />
          </div>
        </div>
      </div>
      
      <div v-if="currentTask" class="history-content">
        <el-timeline>
          <el-timeline-item
            v-for="(activity, index) in taskHistory"
            :key="index"
            :timestamp="activity.timestamp"
            :type="activity.type"
            :color="activity.color"
            :size="activity.important ? 'large' : 'normal'"
            :hollow="activity.hollow"
          >
            <h4 class="timeline-title">{{ activity.title }}</h4>
            <p class="timeline-content">{{ activity.content }}</p>
            
            <div v-if="activity.changes && activity.changes.length > 0" class="change-details">
              <div v-for="(change, cIndex) in activity.changes" :key="cIndex" class="change-item">
                <template v-if="change.field && change.from !== undefined && change.to !== undefined">
                  <span class="field-name">{{ getFieldLabel(change.field) }}: </span>
                  <span class="change-value">
                    <span class="from-value">{{ formatFieldValue(change.field, change.from) }}</span>
                    <el-icon><ArrowRight /></el-icon>
                    <span class="to-value">{{ formatFieldValue(change.field, change.to) }}</span>
                  </span>
                </template>
                <template v-else>
                  {{ change }}
                </template>
              </div>
            </div>
            
            <div class="activity-footer">
              <span class="operator" v-if="activity.operator">
                操作人：{{ activity.operator }}
              </span>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="historyDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { Plus, Warning, WarningFilled, Clock, ArrowRight } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const projectId = ref('')
const status = ref('')
const priority = ref('')
const dialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const dialogType = ref('add')
const taskFormRef = ref(null)
const taskToDelete = ref(null)

// 添加历史记录相关的状态
const historyDialogVisible = ref(false)
const currentTask = ref(null)
const taskHistory = ref([])

// 表单验证规则
const taskRules = {
  name: [
    { required: true, message: '请输入任务名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  projectId: [
    { required: true, message: '请选择所属项目', trigger: 'change' }
  ],
  manager: [
    { required: true, message: '请选择负责人', trigger: 'change' }
  ],
  deadline: [
    { type: 'date', required: true, message: '请选择截止日期', trigger: 'change' }
  ]
}

const taskForm = ref({
  id: '',
  name: '',
  projectId: '',
  projectName: '',
  manager: '',
  deadline: '',
  description: '',
  remarks: '',
  priority: '一般任务',
  status: 'pending',
  statusText: '待处理',
  progress: 0
})

const projects = [
  { id: 1, name: '变电站电气安装工程' },
  { id: 2, name: '配电室改造项目' },
  { id: 3, name: '生产线电气升级' }
]

const users = [
  { id: 1, name: '张三' },
  { id: 2, name: '李四' },
  { id: 3, name: '王五' },
  { id: 4, name: '赵六' }
]

const tasks = ref([
  {
    id: 1,
    name: '主变压器安装',
    projectId: 1,
    projectName: '变电站电气安装工程',
    manager: '张三',
    deadline: '2024-02-28',
    description: '负责主变压器的安装、调试和验收，确保设备正常运行。',
    remarks: '需要协调设备供应商提供现场技术支持。',
    priority: '关键任务',
    status: 'active',
    statusText: '进行中',
    progress: 60
  },
  {
    id: 2,
    name: '高压开关柜安装',
    projectId: 1,
    projectName: '变电站电气安装工程',
    manager: '李四',
    deadline: '2024-03-10',
    description: '安装配电室高压开关柜，连接电缆并进行测试。',
    remarks: '',
    priority: '关键任务',
    status: 'pending',
    statusText: '待处理',
    progress: 0
  },
  {
    id: 3,
    name: '配电柜安装',
    projectId: 2,
    projectName: '配电室改造项目',
    manager: '李四',
    deadline: '2024-03-15',
    description: '拆除旧配电柜，安装新配电柜并完成接线工作。',
    remarks: '',
    priority: '一般任务',
    status: 'active',
    statusText: '进行中',
    progress: 35
  },
  {
    id: 4,
    name: '控制系统调试',
    projectId: 3,
    projectName: '生产线电气升级',
    manager: '王五',
    deadline: '2024-04-01',
    description: '对自动化控制系统进行调试和优化，确保生产线正常运行。',
    remarks: '需要与生产部门协调测试时间。',
    priority: '普通任务',
    status: 'completed',
    statusText: '已完成',
    progress: 100
  },
  {
    id: 5,
    name: '低压配电盘接线',
    projectId: 2,
    projectName: '配电室改造项目',
    manager: '赵六',
    deadline: '2024-03-05',
    description: '根据设计图纸完成低压配电盘的接线工作。',
    remarks: '',
    priority: '一般任务',
    status: 'active',
    statusText: '进行中',
    progress: 75
  },
  {
    id: 6,
    name: '电能质量分析仪安装',
    projectId: 3,
    projectName: '生产线电气升级',
    manager: '王五',
    deadline: '2024-03-20',
    description: '安装电能质量分析仪，监测设备运行情况。',
    remarks: '',
    priority: '普通任务',
    status: 'pending',
    statusText: '待处理',
    progress: 0
  }
])

// 根据筛选条件过滤任务
const filteredTasks = computed(() => {
  return tasks.value.filter(task => {
    const projectMatch = !projectId.value || Number(task.projectId) === Number(projectId.value)
    const statusMatch = !status.value || task.status === status.value
    const priorityMatch = !priority.value || task.priority === priority.value
    return projectMatch && statusMatch && priorityMatch
  })
})

// 获取指定优先级的任务数量
const getTaskCountByPriority = (priorityLevel) => {
  return tasks.value.filter(task => task.priority === priorityLevel).length
}

// 获取优先级对应的类型
const getPriorityType = (priority) => {
  const types = {
    '关键任务': 'danger',
    '一般任务': 'warning',
    '普通任务': 'info'
  }
  return types[priority] || 'info'
}

// 获取优先级标签类型
const getPriorityTagType = (priority) => {
  const types = {
    '关键任务': 'danger',
    '一般任务': 'warning',
    '普通任务': 'info'
  }
  return types[priority] || 'info'
}

// 获取优先级简称
const getPriorityShort = (priority) => {
  const shorts = {
    '关键任务': '关键',
    '一般任务': '一般',
    '普通任务': '普通'
  }
  return shorts[priority] || priority
}

// 获取状态对应的类型
const getStatusType = (status) => {
  const types = {
    'pending': 'info',
    'active': 'primary',
    'completed': 'success'
  }
  return types[status] || 'info'
}

// 获取任务进度
const getTaskProgress = (task) => {
  if (task.status === 'completed') return 100
  return task.progress || 0
}

// 获取进度条状态
const getProgressStatus = (status) => {
  if (status === 'completed') return 'success'
  return ''
}

// 格式化进度提示
const formatProgress = (val) => {
  return `${val}%`
}

// 检查截止日期是否临近(7天内)
const isDeadlineNear = (deadline) => {
  if (!deadline) return false
  
  const today = new Date()
  const deadlineDate = new Date(deadline)
  const diffTime = deadlineDate.getTime() - today.getTime()
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  return diffDays >= 0 && diffDays <= 7
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 显示新增任务对话框
const showAddTaskDialog = () => {
  dialogType.value = 'add'
  taskForm.value = {
    id: '',
    name: '',
    projectId: '',
    projectName: '',
    manager: '',
    deadline: '',
    description: '',
    remarks: '',
    priority: '一般任务',
    status: 'pending',
    statusText: '待处理',
    progress: 0
  }
  dialogVisible.value = true
}

// 编辑任务
const editTask = (task) => {
  dialogType.value = 'edit'
  taskForm.value = { ...task }
  dialogVisible.value = true
}

// 获取项目名称
const getProjectNameById = (projectId) => {
  const project = projects.find(p => p.id === projectId)
  return project ? project.name : ''
}

// 获取状态文本
const getStatusTextByStatus = (status) => {
  const texts = {
    'pending': '待处理',
    'active': '进行中',
    'completed': '已完成'
  }
  return texts[status] || '未知状态'
}

// 保存任务
const saveTask = () => {
  taskFormRef.value.validate((valid) => {
    if (!valid) return
    
    // 设置项目名称
    taskForm.value.projectName = getProjectNameById(taskForm.value.projectId)
    
    // 设置状态文本
    taskForm.value.statusText = getStatusTextByStatus(taskForm.value.status)
    
    // 如果状态是已完成，则进度设为100%
    if (taskForm.value.status === 'completed') {
      taskForm.value.progress = 100
    }
    
    if (dialogType.value === 'add') {
      // 添加新任务
      taskForm.value.id = Date.now() // 模拟生成ID
      tasks.value.push({ ...taskForm.value })
      ElMessage.success('任务添加成功')
    } else {
      // 更新现有任务
      const index = tasks.value.findIndex(t => t.id === taskForm.value.id)
      if (index !== -1) {
        tasks.value[index] = { ...taskForm.value }
        ElMessage.success('任务更新成功')
      }
    }
    
    dialogVisible.value = false
  })
}

// 完成任务
const completeTask = (task) => {
  ElMessageBox.confirm(`确认将任务"${task.name}"标记为已完成？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(() => {
    const index = tasks.value.findIndex(t => t.id === task.id)
    if (index !== -1) {
      tasks.value[index].status = 'completed'
      tasks.value[index].statusText = '已完成'
      tasks.value[index].progress = 100
      ElMessage.success('任务已标记为完成')
    }
  }).catch(() => {})
}

// 删除任务
const deleteTask = (task) => {
  taskToDelete.value = task
  deleteDialogVisible.value = true
}

// 确认删除
const confirmDelete = () => {
  const index = tasks.value.findIndex(t => t.id === taskToDelete.value.id)
  if (index !== -1) {
    tasks.value.splice(index, 1)
    ElMessage.success('任务已删除')
    deleteDialogVisible.value = false
  }
}

// 从表单中确认删除
const confirmDeleteFromForm = () => {
  dialogVisible.value = false
  taskToDelete.value = { ...taskForm.value }
  deleteDialogVisible.value = true
}

// 显示任务历史记录
const showTaskHistory = (task) => {
  currentTask.value = task
  generateTaskHistory(task)
  historyDialogVisible.value = true
}

// 生成任务历史记录（模拟数据）
const generateTaskHistory = (task) => {
  // 在实际应用中，这些数据应该从后端API获取
  const history = []
  
  // 创建任务记录
  history.push({
    title: '创建任务',
    content: `创建了任务 "${task.name}"`,
    timestamp: getRandomPastDate(90),
    type: 'primary',
    color: '#409EFF',
    operator: '李四',
    important: true,
    changes: [
      { field: 'name', from: '', to: task.name },
      { field: 'projectId', from: '', to: task.projectId },
      { field: 'deadline', from: '', to: task.deadline }
    ]
  })
  
  // 如果任务有描述，添加描述修改记录
  if (task.description) {
    history.push({
      title: '更新任务描述',
      content: '更新了任务描述',
      timestamp: getRandomPastDate(80),
      type: 'info',
      color: '#909399',
      operator: task.manager,
      changes: [
        { field: 'description', from: '无描述', to: task.description }
      ]
    })
  }
  
  // 根据任务状态添加状态变更记录
  if (task.status === 'active' || task.status === 'completed') {
    history.push({
      title: '开始处理任务',
      content: '任务状态从"待处理"变更为"进行中"',
      timestamp: getRandomPastDate(70),
      type: 'warning',
      color: '#E6A23C',
      operator: task.manager,
      changes: [
        { field: 'status', from: 'pending', to: 'active' }
      ]
    })
  }
  
  // 如果任务进度大于0且小于100，添加进度更新记录
  if (task.progress > 0 && task.progress < 100) {
    const progressSteps = Math.min(Math.floor(task.progress / 20), 4)
    for (let i = 1; i <= progressSteps; i++) {
      const prevProgress = (i - 1) * 20
      const newProgress = i * 20
      history.push({
        title: '更新任务进度',
        content: `任务进度更新至 ${newProgress}%`,
        timestamp: getRandomPastDate(60 - i * 10),
        type: '',
        color: '#67C23A',
        operator: task.manager,
        changes: [
          { field: 'progress', from: prevProgress, to: newProgress }
        ]
      })
    }
    
    // 添加最新的进度更新
    if (task.progress > progressSteps * 20) {
      history.push({
        title: '更新任务进度',
        content: `任务进度更新至 ${task.progress}%`,
        timestamp: getRandomPastDate(15),
        type: '',
        color: '#67C23A',
        operator: task.manager,
        changes: [
          { field: 'progress', from: progressSteps * 20, to: task.progress }
        ]
      })
    }
  }
  
  // 如果任务已完成，添加完成记录
  if (task.status === 'completed') {
    history.push({
      title: '完成任务',
      content: '任务已标记为完成',
      timestamp: getRandomPastDate(5),
      type: 'success',
      color: '#67C23A',
      operator: task.manager,
      important: true,
      changes: [
        { field: 'status', from: 'active', to: 'completed' },
        { field: 'progress', from: task.progress < 100 ? task.progress : 90, to: 100 }
      ]
    })
  }
  
  // 如果任务有备注，添加备注更新记录
  if (task.remarks) {
    history.push({
      title: '添加备注',
      content: '为任务添加了备注信息',
      timestamp: getRandomPastDate(40),
      type: 'info',
      color: '#909399',
      operator: task.manager,
      changes: [
        { field: 'remarks', from: '', to: task.remarks }
      ]
    })
  }
  
  // 添加一些通用的更新记录
  if (task.priority === '关键任务') {
    history.push({
      title: '提升优先级',
      content: '将任务优先级提升为"关键任务"',
      timestamp: getRandomPastDate(50),
      type: 'danger',
      color: '#F56C6C',
      operator: '项目经理',
      important: true,
      changes: [
        { field: 'priority', from: '一般任务', to: '关键任务' }
      ]
    })
  }
  
  // 如果截止日期临近，添加提醒记录
  if (isDeadlineNear(task.deadline)) {
    history.push({
      title: '截止日期提醒',
      content: '系统自动提醒：任务将在7天内到期',
      timestamp: getRandomPastDate(3),
      type: 'warning',
      color: '#E6A23C',
      operator: '系统',
      hollow: true,
      changes: []
    })
  }
  
  // 按时间排序（从新到旧）
  taskHistory.value = history.sort((a, b) => 
    new Date(b.timestamp) - new Date(a.timestamp)
  )
}

// 生成随机过去的日期
const getRandomPastDate = (maxDaysAgo) => {
  const today = new Date()
  const randomDays = Math.floor(Math.random() * maxDaysAgo)
  const date = new Date(today)
  date.setDate(today.getDate() - randomDays)
  
  // 格式化日期时间
  return formatDateTime(date)
}

// 格式化日期时间
const formatDateTime = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 获取字段显示名称
const getFieldLabel = (field) => {
  const labels = {
    'name': '任务名称',
    'projectId': '所属项目',
    'manager': '负责人',
    'deadline': '截止日期',
    'description': '任务描述',
    'remarks': '备注',
    'priority': '优先级',
    'status': '状态',
    'progress': '进度'
  }
  return labels[field] || field
}

// 格式化字段值
const formatFieldValue = (field, value) => {
  if (field === 'projectId') {
    return getProjectNameById(value) || value
  } else if (field === 'status') {
    return getStatusTextByStatus(value) || value
  } else if (field === 'progress') {
    return `${value}%`
  } else if (field === 'deadline' && value) {
    return formatDate(value)
  } else {
    return value === '' ? '无' : value
  }
}
</script>

<style lang="scss" scoped>
.tasks-container {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    .page-title {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
      color: #303133;
    }
    
    .summary-stats {
      display: flex;
      gap: 24px;
      
      .stat-item {
        text-align: center;
        
        .stat-value {
          display: block;
          font-size: 24px;
          font-weight: bold;
          
          &.critical {
            color: #F56C6C;
          }
          
          &.important {
            color: #E6A23C;
          }
          
          &.normal {
            color: #909399;
          }
        }
        
        .stat-label {
          font-size: 14px;
          color: #606266;
        }
      }
    }
  }
  
  .filter-bar {
    background-color: #f5f7fa;
    padding: 16px;
    border-radius: 8px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .filter-group {
      display: flex;
      gap: 16px;
      
      .filter-item {
        width: 180px;
      }
    }
    
    .add-button {
      min-width: 120px;
    }
  }
  
  .task-name-cell {
    display: flex;
    align-items: center;
    
    .priority-tag {
      margin-right: 8px;
    }
    
    .task-name {
      font-weight: 500;
    }
  }
  
  .manager-cell {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  
  .deadline-cell {
    display: flex;
    align-items: center;
    gap: 5px;
    
    &.deadline-warning {
      color: #E6A23C;
      
      .el-icon {
        color: #E6A23C;
      }
    }
  }
  
  .task-detail {
    padding: 16px;
    background-color: #f9f9f9;
    border-radius: 4px;
    margin: 10px;
    
    .detail-item {
      margin-bottom: 10px;
      
      label {
        font-weight: bold;
        color: #606266;
        margin-right: 5px;
      }
      
      span {
        color: #303133;
      }
    }
  }
  
  .delete-confirm {
    text-align: center;
    padding: 20px 0;
    
    .warning-icon {
      font-size: 48px;
      color: #E6A23C;
      margin-bottom: 16px;
    }
    
    p {
      margin: 8px 0;
      font-size: 16px;
    }
    
    .warning-text {
      color: #F56C6C;
      font-weight: bold;
    }
  }

  // 添加历史记录相关样式
  .action-buttons {
    display: flex;
    gap: 8px;
    justify-content: center;
  }

  .task-history-header {
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
    
    h3 {
      margin-top: 0;
      margin-bottom: 12px;
      font-size: 18px;
      color: #303133;
    }
    
    .task-basic-info {
      display: flex;
      flex-wrap: wrap;
      gap: 15px;
      
      .info-item {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        
        .label {
          color: #606266;
          margin-right: 5px;
          font-weight: 500;
        }
      }
    }
  }

  .history-content {
    max-height: 400px;
    overflow-y: auto;
    padding-right: 10px;
    
    .timeline-title {
      font-size: 16px;
      margin: 0 0 8px;
      color: #303133;
    }
    
    .timeline-content {
      color: #606266;
      margin: 0 0 8px;
    }
    
    .change-details {
      background-color: #f8f8f8;
      border-radius: 4px;
      padding: 10px;
      margin-bottom: 10px;
      
      .change-item {
        margin-bottom: 5px;
        font-size: 13px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .field-name {
          color: #909399;
          font-weight: 500;
        }
        
        .change-value {
          display: inline-flex;
          align-items: center;
          
          .from-value {
            color: #F56C6C;
            padding: 0 3px;
          }
          
          .to-value {
            color: #67C23A;
            padding: 0 3px;
          }
          
          .el-icon {
            margin: 0 5px;
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }
    
    .activity-footer {
      display: flex;
      justify-content: flex-end;
      
      .operator {
        font-size: 12px;
        color: #909399;
      }
    }
  }
}
</style> 